package com.yuntoyun.fwcore.base;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.TieBean;
import com.dou361.dialogui.listener.DialogUIItemListener;
import com.yalantis.ucrop.UCrop;
import com.yuntoyun.fwcore.appext.data.FwAppPathData;
import com.yuntoyun.fwcore.base.ext.BaseTakePhotoCallback;
import com.yuntoyun.fwcore.base.ext.GifSizeFilter;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwSizeUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.functions.Consumer;

/**
 * 应用 基于Matisse插件的TakePhoto组件 Activity 基础类
 */
public abstract class FwBaseTakePhotoByMatisseActivity extends FwBaseActivity implements BaseTakePhotoCallback {

    private static final String TAG = FwBaseTakePhotoByMatisseActivity.class.getSimpleName();

    private static final int MATISSE_SINGLE_CHOOSE_CODE = 9900;
    private static final int MATISSE_MULTIPLE_CHOOSE_CODE = 9901;
    private static final int MATISSE_CAMERA_CHOOSE_CODE = 9902;

    private int pxOfOneDp = 0;
    private Uri cameraUri;


    protected abstract void initChildView();

    @Override
    protected void initView() {
        pxOfOneDp = FwSizeUtil.builder().dpToPx(fwActivity, 1);
        //加载视图
        initChildView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) return;

        //图片拾取
        switch (requestCode) {
            case MATISSE_SINGLE_CHOOSE_CODE:
                //单选逻辑
                List<Uri> listUri = Matisse.obtainResult(data);
                List<String> listPath = Matisse.obtainPathResult(data);
                FwLogUtil.info("相册》图片路径》" + listUri.get(0));
                openCropImage(listUri.get(0));
                break;
            case MATISSE_MULTIPLE_CHOOSE_CODE:
                //多选逻辑
                List<Uri> listUriM = Matisse.obtainResult(data);
                List<String> listPathM = Matisse.obtainPathResult(data);
                takePhotoMultipleCallback(listUriM, listPathM);
                break;
            case MATISSE_CAMERA_CHOOSE_CODE:
//                //图片Bitmap
//                try {
//                    Bitmap mImageBitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), cameraUri);
//                    //iv.setImageBitmap(mImageBitmap);
//                } catch (IOException e) {
//                    FwLogUtil.error(TAG, e);
//                } catch (Exception e) {
//                    FwLogUtil.error(TAG, e);
//                }
                //其他处理
                FwLogUtil.info("照相机》图片路径》" + cameraUri.toString());
                openCropImage(cameraUri);
                break;
        }
        //切图处理
        switch (requestCode) {
            case UCrop.REQUEST_CROP:
                //切图处理
                final Uri resultUri = UCrop.getOutput(data);
                FwLogUtil.info("截图工具》图片路径》" + resultUri.toString());
                takePhotoSingleCallback(resultUri);
                break;
            case UCrop.RESULT_ERROR:
                final Throwable cropError = UCrop.getError(data);
                if (cropError != null) {
                    FwLogUtil.error(TAG, cropError.getMessage());
                }
                FwLogUtil.info("截图工具》操作异常");
                break;
        }
    }

    protected void doFilePicker() {
        this.doFilePickerV();
    }

    /**
     * 选择文件
     */
    protected void doFilePickerV() {

        fwRxPermissionUtil.usePermission(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean granded) throws Exception {
                if (granded) {
                    fwRxPermissionUtil.usePermission(granded2 -> {
                        if (granded2) {
                            List<TieBean> options = new ArrayList<TieBean>();

//                            if (null == openTypeList) {
                            options.add(new TieBean("拍照", 1));
                            options.add(new TieBean("从相册选择", 3));
//                            } else {
//                                for (FwGalleryFinalTool.OpenType openType : openTypeList) {
//                                    if (openType == FwGalleryFinalTool.OpenType.Camera)
//                                        options.add(new TieBean("拍照", 0)); //拍照
//                                    if (openType == FwGalleryFinalTool.OpenType.CameraCrop)
//                                        options.add(new TieBean("拍照", 1)); //拍照截图
//                                    if (openType == FwGalleryFinalTool.OpenType.Single)
//                                        options.add(new TieBean("从相册选择", 2)); //从相册选择（单选）
//                                    if (openType == FwGalleryFinalTool.OpenType.SingleCrop)
//                                        options.add(new TieBean("从相册选择", 3)); //从相册选择截图（单选）
//                                    if (openType == FwGalleryFinalTool.OpenType.Multiple)
//                                        options.add(new TieBean("从相册选择", 4)); //从相册选择（多选）
//                                    if (openType == FwGalleryFinalTool.OpenType.MultipleCrop)
//                                        options.add(new TieBean("从相册选择", 5)); //从相册选择截图（多选）
//                                    if (openType == FwGalleryFinalTool.OpenType.CameraVideo)
//                                        options.add(new TieBean("录像", 6)); //录像
//                                    if (openType == FwGalleryFinalTool.OpenType.SingleVideo)
//                                        options.add(new TieBean("从相册选择", 7)); //录像选择（单选）
//                                    if (openType == FwGalleryFinalTool.OpenType.MultipleVideo)
//                                        options.add(new TieBean("从相册选择", 8)); //录像选择（多选）
//                                }
//                            }

                            DialogUIUtils.showSheet(fwActivity, options, "取消", Gravity.BOTTOM, true, true,
                                    new DialogUIItemListener() {
                                        @Override
                                        public void onItemClick(CharSequence text, int position) {
                                            switch (options.get(position).getId()) {
                                                case 0:

                                                    break;
                                                case 1://拍照截图（可用）
                                                    openCropCamera();
                                                    break;
                                                case 2:

                                                    break;
                                                case 3://从相册单选截图（）
                                                    Matisse.from(fwActivity)
                                                            .choose(MimeType.ofImage())
                                                            .countable(false)
                                                            .capture(true)
                                                            .captureStrategy(new CaptureStrategy(true, fwActivity.getPackageName() + ".afcore.fileProvider", "temp"))
                                                            .maxSelectable(1)
                                                            .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                                            .gridExpectedSize(getResources().getDimensionPixelSize(pxOfOneDp * 120))
                                                            .gridExpectedSize(pxOfOneDp * 120)
                                                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                                            .thumbnailScale(0.85f)
                                                            .imageEngine(new GlideEngine())
                                                            .showSingleMediaType(true)
                                                            .showPreview(false) // Default is `true`
                                                            .forResult(MATISSE_SINGLE_CHOOSE_CODE);
                                                    break;
                                                case 4:

                                                    break;
                                                case 5:

                                                    break;
                                                case 6:

                                                    break;
                                                case 7:

                                                    break;
                                                case 8:

                                                    break;
                                            }
                                        }

                                        @Override
                                        public void onBottomBtnClick() {
                                            super.onBottomBtnClick();
                                        }
                                    }).show();
                        } else {
                            FwAlertDialogUtil.builder().showAlertDialog(fwActivity, "警告",
                                    "请开启照相机权限!");
                        }
                    }, Manifest.permission.CAMERA);
                } else {
                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "警告", "请开启存储权限!");
                }
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 获得照片的输出保存Uri
     *
     * @return
     */
    protected Uri getImageCropUri() {
        File file = new File(FwAppPathData.init().getCropImgPath() + System.currentTimeMillis() +
                ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    private UCrop initBasisConfig(UCrop uCrop) {
        /////////
        ///图片比例
        /////////
//        //自定义比例
//        float ratioX = Float.valueOf("5");
//        float ratioY = Float.valueOf("3");
//        uCrop = uCrop.withAspectRatio(ratioX, ratioY);
//        //图片原始比像
//        uCrop = uCrop.useSourceImageAspectRatio();
//        //正方形
//        uCrop = uCrop.withAspectRatio(1, 1);
//        //默认动态（定义）

        /////////
        ///图片尺寸
        /////////
        int maxWidth = 1080;
        int maxHeight = 2400;
        uCrop = uCrop.withMaxResultSize(maxWidth, maxHeight);
        return uCrop;
    }

    private UCrop initAdvancedConfig(UCrop uCrop) {
//        ucropOptions = new UCrop.Options();
//        ucropOptions.setToolbarTitle("裁剪图片");
//        int primaryColor = fwActivity.getResources().getColor(R.color.appThemeColor);
//        int accentColor = fwActivity.getResources().getColor(R.color.appTxtBlackColor);
//        ucropOptions.setToolbarColor(primaryColor);
//        ucropOptions.setStatusBarColor(accentColor);
//        ucropOptions.setToolbarWidgetColor(primaryColor);
//        ucropOptions.setToolbarCancelDrawable(R.mipmap.fw_icon_action_matisse_cancel);
//        ucropOptions.setToolbarCropDrawable(R.mipmap.fw_icon_action_matisse_ok);
//        ucropOptions.setAspectRatioOptions(0, new AspectRatio[]{
//                new AspectRatio("原始图形", 0, 0),
//                new AspectRatio("正方形", 400, 400),
//                new AspectRatio("长方形", 400, 800)
//        });
//        ucropOptions.setActiveControlsWidgetColor(primaryColor);
//        ucropOptions.withMaxResultSize(1080, 2000);
//        ucropOptions.setMaxBitmapSize(1024 * 1024 * 1);

        //原平台代码
        UCrop.Options options = new UCrop.Options();

        /////////
        ///图片压缩
        /////////
//        options.setCompressionFormat(Bitmap.CompressFormat.PNG);
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        /////////
        ///图片质量
        /////////
        options.setCompressionQuality(90);//最大100

        /////////
        ///图片压缩
        /////////
        options.setHideBottomControls(false);//隐藏底部工具栏
        /////////
        ///图片缩放()
        /////////
        options.setFreeStyleCropEnabled(false);
        /*
        If you want to configure how gestures work for all UCropActivity tabs

        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        * */

        /*
        This sets max size for bitmap that will be decoded from source Uri.
        More size - more memory allocation, default implementation uses screen diagonal.

        options.setMaxBitmapSize(640);
        * */
        options.setMaxBitmapSize(640);

       /*

        Tune everything (ﾉ◕ヮ◕)ﾉ*:･ﾟ✧

        options.setMaxScaleMultiplier(5);
        options.setImageToCropBoundsAnimDuration(666);
        options.setDimmedLayerColor(Color.CYAN);
        options.setCircleDimmedLayer(true);
        options.setShowCropFrame(false);
        options.setCropGridStrokeWidth(20);
        options.setCropGridColor(Color.GREEN);
        options.setCropGridColumnCount(2);
        options.setCropGridRowCount(1);
        options.setToolbarCropDrawable(R.drawable.your_crop_icon);
        options.setToolbarCancelDrawable(R.drawable.your_cancel_icon);

        // Color palette
        options.setToolbarColor(ContextCompat.getColor(this, R.color.your_color_res));
        options.setStatusBarColor(ContextCompat.getColor(this, R.color.your_color_res));
        options.setToolbarWidgetColor(ContextCompat.getColor(this, R.color.your_color_res));
        options.setRootViewBackgroundColor(ContextCompat.getColor(this, R.color.your_color_res));
        options.setActiveControlsWidgetColor(ContextCompat.getColor(this, R.color.your_color_res));

        // Aspect ratio options
        options.setAspectRatioOptions(1,
            new AspectRatio("WOW", 1, 2),
            new AspectRatio("MUCH", 3, 4),
            new AspectRatio("RATIO", CropImageView.DEFAULT_ASPECT_RATIO, CropImageView.DEFAULT_ASPECT_RATIO),
            new AspectRatio("SO", 16, 9),
            new AspectRatio("ASPECT", 1, 1));

       */

        return uCrop.withOptions(options);
    }

    //格式化文件路径
    private String getCallbackFilePath(String filePath) {
        if (filePath.startsWith("file://")) {
            filePath = filePath.replace("file://", "");
        }
        return filePath;
    }

    private void openCropCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (captureIntent.resolveActivity(fwActivity.getPackageManager()) != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            String filename = String.format("camera_%s", dateFormat.format(new Date()));
            //文件路径
            File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            File tmpFileImage = null;
            try {
                tmpFileImage = File.createTempFile(filename, ".jpg", storageDir);
            } catch (IOException e) {
                FwLogUtil.error(TAG, e);
            } catch (Exception e) {
                FwLogUtil.error(TAG, e);
            }
            //文件路径
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                cameraUri = Uri.fromFile(tmpFileImage);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
            } else {

                cameraUri = FileProvider.getUriForFile(fwActivity, fwActivity.getPackageName() + ".afcore.fileProvider", tmpFileImage);

                ContentValues contentValues = new ContentValues();
//                contentValues.put(MediaStore.Images.Media.DATA, tmpFileImage.getAbsolutePath());
                //默认系统相机位置
                contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
                contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                cameraUri = fwActivity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
            }
            fwActivity.startActivityForResult(captureIntent, MATISSE_CAMERA_CHOOSE_CODE);
        } else {
            FwLogUtil.warn(TAG, "设备不存在相机功能！");
        }
    }

    private String getUriByCamera() {
        String[] projection = {
                MediaStore.MediaColumns._ID,
                MediaStore.Images.ImageColumns.ORIENTATION,
                MediaStore.Images.Media.DATA
        };
        Cursor cursor = getContentResolver().query(cameraUri, projection, null, null, null);
        cursor.moveToFirst();
//        final String[] SCAN_TYPES = {"image/jpeg"};
//        MediaScannerConnection.scanFile(fwActivity, new String[]{cameraUri.toString()}, SCAN_TYPES, null);
        return cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
    }

    private void openCropImage(@NonNull Uri source) {
        Uri destination = getImageCropUri();
        FwLogUtil.info(String.format("启动裁剪》源路径==%s|||目录路径==%s", source.toString(), destination.toString()));

        UCrop uCrop = UCrop.of(source, destination);
        uCrop = initBasisConfig(uCrop);
        uCrop = initAdvancedConfig(uCrop);
        uCrop.start(fwActivity);
    }

    //======================================================================

    public void setFwMaxLimitNum(int fwMaxLimitNum) {

    }
}
